import React, { useState, useEffect } from 'react'
import styles from '../../styles/home/classShow.scss'
import { Popover } from 'antd';
import Header from './Header'
import { axiosConfig, backIP, error, IconFont } from '../common/config'
import axios from 'axios'
import { getToken } from '../common/util'
import Router from 'next/router'

export default function ClassShow() {
    const [houseID, setHouseId] = useState(null)
    const [floor, setFloor] = useState(null)
    const [isHasClass, setIsHasClass] = useState(false)
    const [classInfo, setClassInfo] = useState([])

    const getBasicClassInfo = async () => {
        const token: string = getToken();
        if (!(houseID && floor)) {
            setClassInfo([])
            setIsHasClass(false)
            return
        }
        const { data: res }: { data: axiosConfig } = await axios.get(`${backIP}/basicClass`, {
            params: {
                house_id: houseID,
                floor: floor
            },
            headers: {
                Authorization: token,
            }
        })
        if (res.code === 0) {
            if (res.data.length === 0) {
                setIsHasClass(false)
            } else {
                setIsHasClass(true)
            }
            setClassInfo(res.data)
        } else {
            error(res.message)
        }
    }
    const generateTip = (name: string, seatNum: string) => {
        return <div>
            <p>教室名：{name}</p>
            <p>座位数：{seatNum}</p>
        </div>
    }
    const handleClickClass = (classID: number) => {
        Router.push({
            pathname: '/classroom',
            query: {
                class: classID
            }
        })
    }

    useEffect(() => {
        getBasicClassInfo()
    }, [houseID, floor])
    return (
        <div className={styles.layout}>
            <Header setHouseID={setHouseId} setFloor={setFloor} />
            {
                isHasClass ?
                    <div className={styles.main}>
                        {
                            classInfo.map((item, index) => {
                                return <Popover
                                    content={generateTip(item.class_name, item.seat_number)}
                                    title="教室信息"
                                    trigger="hover"
                                    key={index}
                                >
                                    <IconFont type='iconicon' className={styles.icon} onClick={() => { handleClickClass(item.class_id) }} />
                                </Popover>
                            })
                        }
                    </div>
                    : <div className={styles.empty}>没有教室信息</div>

            }
        </div>
    )
}
